package top.infopub.mgc.core.sender.sms;


import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import top.infopub.common.ErrorCodeEnum;
import top.infopub.httpclient.base.HttpBizRsp;
import top.infopub.httpclient.proxy.HttpClientProxy;
import top.infopub.mgc.core.domain.PartnerInfoDomain;
import top.infopub.mgc.core.service.PartnerInfoService;
import top.infopub.mgc.util.EnviornConfig;
import top.infopub.util.DateUtil;
import top.infopub.util.Dom4JUtil;
import top.infopub.util.MD5;
import top.infopub.vo.ResponseVo;

import com.google.common.collect.Maps;


/**
 * 骥凡供应商-短信发送工具类-- 弃用供应商
 * @author Awoke
 * @version 2018-10-14
 * @see SmsSenderJf
 * @since
 */
@Component
public class SmsSenderJf {

    private static final Logger log = LoggerFactory.getLogger(SmsSenderJf.class);

    @Resource
    private EnviornConfig env;

    @Autowired
    private PartnerInfoService partnerInfoService;

    /** partner-code **/
    private static final String PARTNER_CODE_SMS_JF = "MGC_PARTNER_SMS_JF";

    /**
     * 下发短信 <br/>
     * @param mobiles   手机号  多个号码用”,”分隔
     * @param content   短信内容
     * @see
     */
    @SuppressWarnings("unchecked")
    public ResponseVo<String> sendMessage(String mobiles, String content) {
        try {
            if (!env.isProduction()) {
                return ResponseVo.getSuccessResponse();
            }
            PartnerInfoDomain partnerInfo = partnerInfoService.getPartnerCache(PARTNER_CODE_SMS_JF);
            PartnerInfoDomain.Sms smsInfo = partnerInfo.getSms();
            Map<String, String> maps = Maps.newHashMap();
            maps.put("userid", smsInfo.getSpCode());// 企业id
            String timestamp = DateUtil.currentDate("yyyyMMddHHmmss");
            maps.put("timestamp", timestamp);// 时间戳
            // 签名  账号+密码+时间戳 生成MD5字符串作为签名。MD5生成32位，且需要小写
            maps.put(
                "sign",
                MD5.encode(partnerInfo.getSpartnerAccName() + partnerInfo.getSpartnerAccPassword()
                           + timestamp));
            maps.put("mobile", mobiles); // 手机号码
            maps.put("content", content);// 内容
            maps.put("sendTime", ""); // 定时发送时间  为空表示立即发送
            maps.put("action", "send"); // actionType 
            maps.put("extno", ""); // 扩展子号
            // reqPostFormUTF8
            HttpBizRsp rsp = HttpClientProxy.reqPostFormUTF8(smsInfo.getSendUrl(), maps);
            if (rsp.isOk()) {
                String result = rsp.getData();
                String status = Dom4JUtil.getValueByEleName(result, "returnstatus");
                String msg = Dom4JUtil.getValueByEleName(result, "message");
                // 网关返回结果    返回状态值：成功返回Success 失败返回：Faild。 Success说明下发到网关成功
                log.info("sendSms to:{} >>content:{}  rtnMsg:{}", new Object[] {mobiles, content,
                    msg});
                // 解析返回结果
                if (StringUtils.equals("Success", status)) {
                    return ResponseVo.getSuccessResponse();
                }
                else {
                    // 下发网关失败，直接返回异常
                    return ErrorCodeEnum.ERROR_MGC_SENDSMS.getResponseVo(msg);
                }
            }
            else {
                return ErrorCodeEnum.ERROR_MGC_SENDSMS.getResponseVo(rsp.getData());
            }
        }
        catch (Exception e) {
            log.error("sendMessage error", e);
            return ErrorCodeEnum.ERROR_MGC_SENDSMS.getResponseVo(e.getClass().getName() + " "
                                                                 + e.getMessage());
        }
    }

    /**
     * 非法词查询 <br/>
     * @param content   检测发送内容
     * @see
     */
    @SuppressWarnings("unchecked")
    public ResponseVo<String> illegalWord(String content) {
        try {
            PartnerInfoDomain partnerInfo = partnerInfoService.getPartnerCache(PARTNER_CODE_SMS_JF);
            PartnerInfoDomain.Sms smsInfo = partnerInfo.getSms();
            Map<String, String> maps = Maps.newHashMap();
            maps.put("userid", smsInfo.getSpCode());// 企业id
            String timestamp = DateUtil.currentDate("yyyyMMddHHmmss");
            maps.put("timestamp", timestamp);// 时间戳
            // 签名  账号+密码+时间戳 生成MD5字符串作为签名。MD5生成32位，且需要小写
            maps.put(
                "sign",
                MD5.encode(partnerInfo.getSpartnerAccName() + partnerInfo.getSpartnerAccPassword()
                           + timestamp));
            maps.put("action", "checkkeyword"); // actionType
            maps.put("content", content);// 检测发送内容
            // reqPostFormUTF8
            HttpBizRsp rsp = HttpClientProxy.reqPostFormUTF8(smsInfo.getSendUrl(), maps);
            if (rsp.isOk()) {
                String msg = Dom4JUtil.getValueByEleName(rsp.getData(), "message");
                log.info("content:{}, rtnMsg:{}", content, msg);
                return ResponseVo.getSuccessResponse(msg);
            }
            else {
                return ErrorCodeEnum.ERROR_MGC_SENDSMS.getResponseVo(rsp.getData());
            }
        }
        catch (Exception e) {
            log.error("sendMessage error", e);
            return ErrorCodeEnum.ERROR_MGC_SENDSMS.getResponseVo(e.getClass().getName() + " "
                                                                 + e.getMessage());
        }
    }

}
